var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');
var openId = wx.getStorageSync('openId');
var orderNo = "aaaa";
var detailList = "";
var backDetail = "";
var deliveryFee = 0;
var actualPay = 0;
var areaId = "";
var submitContent = "";
var IDarray = new Array();
var timeArray = new Array();
var timeIdArray = new Array();
var deliveryTimeId = "";
var deliveryTimeType = "";
var showSelectArea = "";
var goodOrders = new Array();
var isSelfClaim = "";
var radios = new Array(1, 2);
var alertMsg = new Array();
var reciveName = "";
var recivePhone = "";
var reciveAddress = "";
var reciveAreaId = "";
var reciveArea = "";
var areaIndex = "";//区域picker标号
var payIndex = "";//支付方式标号
var payTypeIdArray = new Array();
var sendTime = "";
var sunbmitCon = "";
var winHeight = "";
var createTime = null;
var leftTime = "";
var totalPrice = 0;
var deliveryFee = 0;
var totalactualPay = 0;
var sendWay = new Array();
var array = new Array(1, 2, 3, 4);
var actualPay = "120.00";
var state = "0";
var paytype = "0";
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
var util = require('../../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hiddenLoading: true,    //loading
    showModal: false,
    paytype: "0",
    deliveryFee: "12.00",
    deliveryAreas: "",
    time: "1",
    radios: radios,
    alertModel: false,
    showTimePicker: false,
    showSelectArea: false,
    ischecked2: true,
    ischecked3: true,
    ischecked1: true,
    selfCheck: true
  },
  bindInputName: function (e) {
    reciveName = e.detail.value;
    this.setData({
      reciveName: reciveName
    })
  },
  bindInputPhone: function (e) {
    recivePhone = e.detail.value
    this.setData({
      recivePhone: recivePhone
    })
  },
  bindInputaddr: function (e) {
    reciveAddress = e.detail.value
    this.setData({
      reciveAddress: reciveAddress
    })
  },
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value);
    for (var j = 0; j < IDarray.length; j++) {
      if (e.detail.value == j) {
        areaId = IDarray[j];
      }
    }
    this.setData({
      areaId: areaId
    })
    this.setData({
      areaIndex: e.detail.value
    })
  },
  //支付方式选择器
  paytypeChange: function (e) {
    paytype = e.detail.value
    this.setData({
      payIndex: e.detail.value,
      paytype: paytype
    })
  },
  bindTimePickerChange: function (e) {
    // console.log("@######3");
    // console.log('picker发送选择改变，携带值为', e.detail.value);
    for (var j = 0; j < timeIdArray.length; j++) {
      if (e.detail.value == j) {
        deliveryTimeId = timeIdArray[j];
      }
    }
    for (var i = 0; i < timeArray.length; i++) {
      if (e.detail.value == i) {
        sendTime = timeArray[i];
      }
    }
    this.setData({
      sendTime: sendTime
    })
    deliveryTimeType = "0";
    showSelectArea = true;
    this.setData({
      showSelectArea: showSelectArea
    })
    this.setData({
      deliveryTimeType: deliveryTimeType
    })
    this.setData({
      deliveryTimeId: deliveryTimeId
    })
    this.setData({
      index: e.detail.value
    })
  },
  parseJson: function jsonToString(data) {
    return JSON.stringify(data);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    goodOrders = new Array();

    var query2 = wx.createSelectorQuery();
    
    deliveryTimeType = "";
    isSelfClaim = "";
    //计算高度
    
    console.log("!!!!!!");
    query2.select('#sunbmitCon').boundingClientRect()
    query2.exec(function (res) {
      wx.getSystemInfo({
        success: function (data) {
          winHeight = data.windowHeight
          console.log(winHeight);
        }
      });
      sunbmitCon = res[0].height;
      console.log("####");
      console.log(sunbmitCon);
      
      console.log("$$$$$$");

      winHeight = winHeight - sunbmitCon
      console.log(winHeight);
      console.log(sunbmitCon);
      that.setData({
        winHeight: winHeight
      });
    });
    
    
    
    var goods = "";
    var spus = new Array();
    yunId = options.yunId,
      openId = options.openId,
      createTime = options.createTime,
      goodOrders = options.goodOrders
    goodOrders = JSON.parse(goodOrders);
    
   
    that.setData({
      yunId: yunId,
      openId: openId
    })
    // that.getleftTime(createTime);
    that.payDetail();
    
  },
  formSubmit: function (e) {
    var that = this;
    var flags = "index";
    if (!myreg.test(e.detail.value.recivePhone)) {
      that.setData({
        is_phone: true        //提示信息
      })
      return;
    } else {
      that.setData({
        is_phone: false   //提示信息
      })
    }

    alertMsg = new Array();
    var flag = true;
    if (e.detail.value.reciveName == "" || e.detail.value.recivePhone == "" || e.detail.value.reciveAddress == "") {
      alertMsg.push("请填写收获信息");
      this.setData({
        alertModel: true
      })
      flag = false;
    }
    //配送方式为配送,必须选中配送区域
    if (isSelfClaim == "" && areaId == "") {
      alertMsg.push("请选择所在社区");
      this.setData({
        alertModel: true
      })
      flag = false;
    }
    //请选择配送方式
    if (deliveryTimeType == "" && isSelfClaim == "") {
      alertMsg.push("请选择配送方式");
      this.setData({
        alertModel: true
      })
      flag = false;
    }
    this.setData({
      alertMsg: alertMsg
    })
    
    if (paytype == "1") {
      var payTyime = util.formatTime(new Date()).toString();
          
          if (flag) {
            //显示加载动画
            that.setData({
              hiddenLoading: false
            });
            wx.request({
              url: apiHost + 'xcx/order/submit?openId=' + openId,
              method: "POST",
              data: {
                openId: openId,
                yunId: yunId,
                payType: paytype,
                isSelfClaim: isSelfClaim,
                deliveryFee: deliveryFee,
                actualPay: actualPay,
                reciveName: e.detail.value.reciveName,
                recivePhone: e.detail.value.recivePhone,
                areaId: areaId,
                reciveAddress: e.detail.value.reciveAddress,
                goodOrders: goodOrders,
                deliveryTimeType: deliveryTimeType,
                deliveryTimeId: deliveryTimeId
              },
              header: {
                'conttent-type': 'application-json'
              },
              success: function (result) {
                
                /**
               * 获取系统信息
               */
                wx.getSystemInfo({
                  success: function (res) {
                    that.setData({
                      hiddenLoading: true
                    });
                  }
                });
                console.log(result)
                if (result.data.code == "10000") {
                  var timeStamp = result.data.data.timeStamp
                  var nonceStr = result.data.data.nonceStr
                  var packages = result.data.data.package
                  var paySign = result.data.data.paySign
                  var signType = result.data.data.signType
                  var appId = result.data.data.appId
                    orderNo = result.data.data.orderNo;
                  //调支付接口
                  wx.requestPayment({
                    appId: appId,
                    timeStamp: timeStamp,
                    nonceStr: nonceStr,
                    'package': packages,
                    signType: signType,
                    paySign: paySign,
                    'success': function (res) {
                      //下单成功后跳转到订单详情页
                      wx.navigateTo({
                        url: '/pages/userOrder/orderDetail/orderDetail?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId + "&flag=" + flags,
                      })
                    },
                    'fail': function (res) {
                    }
                  })
                }else{
                  alertMsg.push(res.data.msg);
                  that.setData({
                    alertModel: true,
                    alertMsg: alertMsg
                  })
                }
                if (result.data.code == "10098") {
                  alertMsg.push("商品库存不足！");
                  that.setData({
                    alertModel: true
                  })
                }
                that.setData({
                  alertMsg: alertMsg
                })
              }
            })
          }
    } else {
      if (flag) {

        //显示加载动画
        that.setData({
          hiddenLoading: false
        });
        wx.request({
          url: apiHost + 'xcx/order/submit?openId=' + openId,
          method: "POST",
          data: {
            openId: openId,
            yunId: yunId,
            payType: paytype,
            isSelfClaim: isSelfClaim,
            deliveryFee: deliveryFee,
            actualPay: actualPay,
            reciveName: e.detail.value.reciveName,
            recivePhone: e.detail.value.recivePhone,
            areaId: areaId,
            reciveAddress: e.detail.value.reciveAddress,
            goodOrders: goodOrders,
            deliveryTimeType: deliveryTimeType,
            deliveryTimeId: deliveryTimeId
          },
          header: {
            'conttent-type': 'application-json'
          },
          success: function (result) {
           
            /**
           * 获取系统信息
           */
            wx.getSystemInfo({
              success: function (res) {
                that.setData({
                  hiddenLoading: true
                });
              }
            });
            if (result.data.code == "10000") {
              console.log("after submit")
              console.log(result)
              orderNo = result.data.data.orderNo;
              //下单成功后跳转到订单详情页
              wx.navigateTo({
                url: '/pages/userOrder/orderDetail/orderDetail?orderNo=' + orderNo + "&yunId=" + yunId + "&openId=" + openId + "&flag=" + flags,
              })
            }
            if (result.data.code == "10098") {
              alertMsg.push("商品库存不足！");
              that.setData({
                alertModel: true
              })
            }
            that.setData({
              alertMsg: alertMsg
            })
          }
        })
      }
    }

  },
  sendChange1: function (e) {
    if (e.detail.value == '1') {
      deliveryTimeType = '1';
      showSelectArea = true;
      this.setData({
        showSelectArea: showSelectArea
      })
      this.setData({
        deliveryTimeType: deliveryTimeType
      })
    }
  },
  changetime: function (e) {
    this.setData({
      showTimePicker: true
    })
  },
  radioSendChange1: function (e) {
    
    var radio = e.currentTarget.dataset.value;
    if (radio == "3") {
      this.setData({
        ischecked3: true
      })
      this.setData({
        showSelectArea: true
      })
      deliveryTimeType = '1';
      isSelfClaim = '0';
    }
    if (radio == "2") {
      this.setData({
        ischecked2: true
      })
      isSelfClaim = '1';
      deliveryTimeType = '';
      this.setData({
        showModal: true
      })
      this.setData({
        showSelectArea: false
      })
    }
  },
  radioSendChange2: function (e) {
    
    var radio = e.currentTarget.dataset.value;
    if (radio == "1") {
      this.setData({
        ischecked1: true,
      })
      this.setData({
        showSelectArea: true
      })
      this.setData({
        showTimePicker: true
      })
      deliveryTimeType = '0';
      isSelfClaim = '0';
    }
    if (radio == "2") {
      this.setData({
        ischecked2: true
      })
      isSelfClaim = '1';
      deliveryTimeType = '';
      this.setData({
        showModal: true
      })
      this.setData({
        showSelectArea: false
      })
    }
  },
  radioSendChange: function (e) {
    
    if (e.detail.value == '1') {
      this.setData({
        showSelectArea: true
      })
      this.setData({
        showTimePicker: true
      })
      isSelfClaim = '0';
    }
    if (e.detail.value == '2') {
      this.setData({
        showSelectArea: false
      })
      isSelfClaim = '1';
      this.setData({
        isSelfClaim: isSelfClaim
      })
      this.setData({
        showModal: true
      })
    }
    if (e.detail.value == '3') {
      this.setData({
        showSelectArea: true
      })
      deliveryTimeType = '1';
      isSelfClaim = '0';
    }
  },
  // 确定选中时间
  TimePickerconfirm: function (e) {
    this.setData({
      showTimePicker: false
    })
  },
  //确认付款
  confirmPay: function (e) {
    wx.redirectTo({
      url: '',
    })
  },
  //取消
  TimePickercancel: function (e) {
    this.setData({
      showTimePicker: false
    })
  },
  confirm: function () {
    this.setData({
      showModal: false,
      alertModel: false,
      is_phone: false
    })
  },
  cancel: function () {
    this.setData({
      showModal: false,
      alertModel: false
    })
  },
  payDetail: function (e) {
    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    wx.request({
      url: apiHost + 'xcx/pay/detail?openId=' + openId,
      method: "POST",
      data: {
        yunId: yunId,
        goodOrders: goodOrders,
        state: state
      },
      header: {
        'conttent-type': 'application-json'
      },
      success: function (res) {

        var array = new Array();
        var payTypearray = new Array();
        for (var i = 0; i < res.data.data.deliveryAreas.length; i++) {
          array.push(res.data.data.deliveryAreas[i].area);
          IDarray.push(res.data.data.deliveryAreas[i].areaId);
        }
        for (var k = 0; k < res.data.data.deliveryTimes.length; k++) {
          var timeIndex = res.data.data.deliveryTimes[k].startTime + "-" + res.data.data.deliveryTimes[k].endTime;
          timeArray.push(timeIndex);//时间展示
          timeIdArray.push(res.data.data.deliveryTimes[k].deliveryTimeId);//时间ID
        }
        
        for (var i = 0; i < res.data.data.payType.length; i++) {
          var paytypeId = res.data.data.payType[i].id;
          var name = res.data.data.payType[i].name;
          payTypearray.push(name);
          payTypeIdArray.push(paytypeId);
        }
        paytype = payTypeIdArray[0]
        if (payTypearray.length == 1) {
          that.setData({
            paytype: paytype
          })
        }
        if (payTypearray.length > 1) {
          paytype = "1";
          that.setData({
            payIndex: paytype
          })

        }
        
        deliveryFee = res.data.data.deliveryFee
        actualPay = res.data.data.actualPay
        //默认数据
        reciveName = res.data.data.reciveName
        recivePhone = res.data.data.recivePhone
        reciveAddress = res.data.data.reciveAddress
        reciveArea = res.data.data.reciveArea
        areaId = res.data.data.reciveAreaId
        for (var i = 0; i < array.length; i++) {
          if (reciveArea == array[i]) {
            areaIndex = i;
            that.setData({
              areaIndex: areaIndex
            })
          }
        }
        that.setData({
          timeIdArray: timeIdArray,
          reciveName: reciveName,
          recivePhone: recivePhone,
          reciveAddress: reciveAddress,
          address: res.data.data.address,
          timeArray: timeArray,
          areaarray: array,
          backDetail: res.data.data,
          isCarry: res.data.data.isCarry,
          deliveryTimeType: res.data.data.deliveryTimeType,
          payTypearray: payTypearray
        })
        

        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              hiddenLoading: true
            });
          }
        });

      }
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})